package com.ivory.valley.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.ivory.valley.common.IvorySession;
import com.ivory.valley.common.IvoryValley;
import com.ivory.valley.common.Resp;
import com.ivory.valley.pojo.User;
import com.ivory.valley.service.UserService;
import com.ivory.valley.util.DateUtil;
import com.ivory.valley.util.HttpUtil;
import com.ivory.valley.util.SessionUtil;

import net.sf.json.JSONObject;

@RestController
@RequestMapping("/auth")
public class AuthController {
	private Logger logger = LoggerFactory.getLogger(AuthController.class);
	private static String url_one = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	private static String url_two = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	private static String url_three = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
	private static String url_four = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	@Autowired
	private UserService userService;
	/**
	 * 用户授权模块
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/auth.dx")
	public void authLogin(HttpServletRequest request ,HttpServletResponse response ,String code,String state) throws UnsupportedEncodingException{
		String openid = null;
		Integer userid = null;
		String nickname = null;
		String sex = null;
		String province = null;
		String city = null;
		String country = null;
		String headimgurl = null;
		String privilege = null;
		//String unionid =null;
		ModelAndView mav = new ModelAndView();
		Map<String, String> result = new HashMap<String, String>();
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			//第二步,通过code换取网页授权access_token
			IvorySession is = SessionUtil.getLogined(request, response);
			if(is != null){
				userid = is.getUserId();
				openid = is.getOpenid();
				nickname =is.getNickname();
				sex = is.getSex();
				province = is.getProvince();
				city = is.getCity();
				country = is.getCountry();
				headimgurl = is.getHeadimgurl();
				privilege = is.getPrivilege();
				if(is.getCheckExpireTime()+7200>DateUtil.getCurrentTimeLong()/1000){
					logger.info("AuthController---------->openid={}", is.getOpenid());
					response.sendRedirect("/ivory-valley/dist/index.html?openid="+openid+"&nickname="+nickname+"&sex="+sex+"&province="+province+"&city="+city+"&country="+country+"&headimgurl="+headimgurl+"&privilege="+privilege);
					return ;
				}
			}
			System.out.println("code============="+code);
			url_two = url_two.replaceAll("APPID", IvoryValley.ConstantAndURL.appid).replaceAll("SECRET", IvoryValley.ConstantAndURL.secret).replaceAll("CODE", code);
			String message2 = HttpUtil.http_get(url_two);
			logger.info("AuthController---------->message2={}", message2);
			JSONObject json = JSONObject.fromObject(message2);
			logger.info("AuthController---------->url_two={}",json.toString());
			String accessToken = json.getString("access_token");
			logger.info("AuthController---------->access_token={}",accessToken);
			String refreshToken = json.getString("refresh_token");
			openid= json.getString("openid");
			//可以根据openid从数据库查询用户信息
			
			//第三步,刷新access_token（如果需要）将acces_token设置有效期30天（当然有必要呀!）
			/*url_three= url_three.replaceAll("APPID", IvoryValley.ConstantAndURL.appid).replaceAll("REFRESH_TOKEN",refreshToken);
			String message3 = HttpUtil.http_get(url_three);
			JSONObject json_three = JSONObject.fromObject(message3);
					
			String refresh_token = json_three.getString("refresh_token");
			System.out.println("refresh_token==============="+refresh_token);*/
			//第四步,拉取用户信息(需scope为 snsapi_userinfo)
			url_four = url_four.replaceAll("ACCESS_TOKEN", accessToken).replaceAll("OPENID", openid);
			String message4 = HttpUtil.http_get(url_four);
			JSONObject json_four = JSONObject.fromObject(message4);
			logger.info("AuthController---------->json_four={}",json_four.toString());
			//考虑将用户信息写进数据库更新
			nickname =URLEncoder.encode(json_four.getString("nickname"), "UTF-8") ;
			sex = "1".equals(json_four.getString("sex"))?"男":"2".equals(json_four.getString("sex"))?"女":"未知";
			province =URLEncoder.encode(json_four.getString("province"), "UTF-8") ;
			city = URLEncoder.encode(json_four.getString("city"), "UTF-8") ;
			country = URLEncoder.encode(json_four.getString("country"), "UTF-8") ;
			headimgurl = json_four.getString("headimgurl");
			privilege = json_four.getString("privilege");
			User user = new User();
			user.setOpenid(openid);
			user.setHeadurl(headimgurl);
			user.setNickname(nickname);
			user.setSex(sex);
			user.setCreateTime(DateUtil.getCurrentTimestamp());
			user.setLoginTime(DateUtil.getCurrentTimestamp());
			user = userService.insetORupdate(user);
			logger.info("AuthController---------->userid={}",user.getId());
			//缓存用户session
			IvorySession iSession = new IvorySession(user.getId());
			iSession.setOpenid(openid);
			iSession.setNickname(nickname);
			iSession.setSex(sex);
			iSession.setProvince(province);
			iSession.setCity(city);
			iSession.setCountry(country);
			iSession.setHeadimgurl(headimgurl);
			iSession.setPrivilege(privilege);
			//创建时间就是用户第一次登录授权的时间，严格来讲是要先查数据库的
			iSession.setCreateTime(Timestamp.valueOf(DateUtil.getCurrentTimeStr()));
			//用户最后一次登录时间，需要写进数据库
			iSession.setLoginTime(Timestamp.valueOf(DateUtil.getCurrentTimeStr()));
			iSession.setCheckExpireTime(DateUtil.getCurrentTimeLong()/1000);
			SessionUtil.setLogined(request, response, iSession);
			response.sendRedirect("/ivory-valley/dist/index.html?openid="+openid+"&nickname="+nickname+"&sex="+sex+"&province="+province+"&city="+city+"&country="+country+"&headimgurl="+headimgurl+"&privilege="+privilege);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/userinfo.dx")
	private Resp<IvorySession> getUserinfo(HttpServletRequest request ,HttpServletResponse response){
		IvorySession is = SessionUtil.getLogined(request, response);
		System.out.println("is="+is+"&logger="+logger);
		//logger.info("AuthController---------->is={}",is);
		Resp<IvorySession> resp = new Resp<IvorySession>();
		if(is != null){
			resp.setRes(is);
			resp.setSuccessCode();
		}else{
			resp.setFailCodeMsg("获取用户信息失败,请重新登录");
		}
		return resp;
	}
}
